package MessageOp;

import UserFriend.FriendConstant;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import java.net.DatagramPacket;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import com.alibaba.fastjson2.JSONWriter;
import serve.Constant;

public class SendMessage
{
    public static void sendMessage(DatagramPacket datagramPacket)
    {
        JSONObject jsonObject = JSONObject.parseObject(new String(datagramPacket.getData()));
        String targetName = jsonObject.getString("targetName");
        JSONObject data = jsonObject.getJSONObject("data");
        String type = data.getString("type");
        String sender = data.getString("sender");

        String data_str = data.toString().replace("\"","\\\"");

        if(type.equals("apply"))
        {
            boolean is_apply_exit = false;
            try
            {
                String sql = "select * from %s where receiver=\"%s\" and type=\"apply\" and sender=\"%s\"";
                sql = String.format(sql,FriendConstant.message_table,targetName,sender);

                Statement stmt = Constant.chatdbConnector.getChatdb_connection().createStatement();
                ResultSet res = stmt.executeQuery(sql);

                is_apply_exit = res.next();
                stmt.close();
            }catch (SQLException e)
            {
                e.printStackTrace();
            }

            if(!is_apply_exit)
            {
                try
                {
                    String sql = "insert into %s(receiver,data,type,sender) values(\"%s\",\"%s\",\"%s\",\"%s\")";
                    sql = String.format(sql,FriendConstant.message_table,targetName,data_str,type,sender);
                    //System.out.print(sql);

                    PreparedStatement stat = Constant.chatdbConnector.getChatdb_connection().prepareStatement(sql);
                    stat.executeUpdate();
                    stat.close();
                }catch (SQLException e)
                {
                    e.printStackTrace();
                }
            }
        }
        else
        {
            try
            {
                String sql = "insert into %s(receiver,data,type,sender) values(\"%s\",\"%s\",\"%s\",\"%s\")";
                sql = String.format(sql,FriendConstant.message_table,targetName,data_str,type,sender);
                //System.out.print(sql);

                PreparedStatement stat = Constant.chatdbConnector.getChatdb_connection().prepareStatement(sql);
                stat.executeUpdate();
                stat.close();
            }catch (SQLException e)
            {
                e.printStackTrace();
            }
        }
    }
}
